package com.hnn.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hnn.types.User;

import java.time.LocalDateTime;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;


/**
 * @author hnn
 * @version 1.0
 * @date 2025-05-12 10:30
 */
@RequiredArgsConstructor
@Service
public class UserService {

    private final ObjectMapper objectMapper;

    @Cacheable(
            value = "userCache#200",          // 缓存名称（必填） #200自定义ttl的一种方式
            key = "#userId",              // 动态生成缓存键（支持参数变量）
            condition = "#userId > 1000", // 仅当 userId > 1000 时缓存
            unless = "#result == null"    // 结果不为 null 时缓存
    )
    public User getUserById(Long userId) {
        User user = new User(userId, "Name " + userId, LocalDateTime.now());
        // 模拟数据库查询
        try {
            System.out.println("Querying user from DB... " + objectMapper.writeValueAsString(user));
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return user;
    }

    @CacheEvict(value = "userCache", key = "#userId")
    public void deleteUserById(Long userId) {
        System.out.println("Deleting user from DB... " + userId);
    }
}
